import moment from 'moment';

export const yearAndMonth = validRange => {
  const today = moment();
  let error = false;
  if (!validRange) {
    validRange = [1990, Number(today.format('YYYY')) + 10];
  }
  if (!validRange[0]) {
    validRange[0] = 1990;
  }
  if (!validRange[1]) {
    validRange[1] = Number(today.format('YYYY')) + 10;
  }
  if (validRange[1] - validRange[0] < 0) {
    console.error('validRange error, need validRange[1] >= validRange[0]');
    validRange = [1990, Number(today.format('YYYY')) + 10];
    error = true;
  }
  const years = [];
  for (let i = validRange[0], end = validRange[1]; i <= end; i++) {
    years.push({
      label: i,
      value: i
    });
  }
  const months = [];
  for (let i = 1; i < 13; i++) {
    months.push({
      label: i,
      value: i
    });
  }

  return {
    yearAndMonth: [years, months],
    validRange: [...validRange],
    error
  };
};
export const isLeap = year => {
  year = Number(year);
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
};
/**
 *
 * @param date moment类型
 */
const month31 = new Set([1, 3, 5, 7, 8, 10, 12]);
export const getMonthWeekDays = date => {
  const year = Number(date.format('YYYY'));
  const week = Number(moment(date.format('YYYY-MM')).format('E'));
  const month = Number(date.format('M'));
  const days = month === 2 ? (isLeap(year) ? 29 : 28) : month31.has(month) ? 31 : 30;
  return {
    week,
    month,
    days
  };
};

export const formatNumberToString = (number, bit = 2) => {
  const str = `000000000000000000${number}`;
  return str.substring(str.length - bit);
};

export const getDays = (week, days) => {
  const num = Number(week) === 7 ? days : week + days;
  const ds = [];
  for (let i = 0; i < num; i++) {
    if (i < week && Number(week) !== 7) {
      ds.push('');
    } else {
      ds.push(Number(week) === 7 ? formatNumberToString(i + 1) : formatNumberToString(i - week + 1));
    }
  }
  return ds;
};
